import React from 'react'
import { Text, View, Image, } from '@tarojs/components'
import { ViewModelProp as P } from '../../types'
import Taro from '@tarojs/taro'

type Props = {
    bind: {
        viewModel: P,
        setViewModel: (intent: Partial<P>) => void
    },
    maxCount?: number,
    width?: string,
    style?: React.CSSProperties,
    itemStyle?: React.CSSProperties,
    addItemStyle?: React.CSSProperties,
    addEnabled?: boolean,
    addIcon?: string,
    addIconStyle?: React.CSSProperties,
    addText?: string | null,
    deleteIcon?: string,
    addView?: React.ReactNode,
    /**外边距 */
    spacingHorizontal?: string,
    /**内边距 */
    spacingInner?: string
}


export default (props: Props) => {
    const {
        addEnabled = true,
        addIcon,
        deleteIcon,
        maxCount = 6,
        addText = '添加图片',
        spacingHorizontal = '15px',
        spacingInner = '8px',
    } = props
    const { viewModel, setViewModel, } = props.bind
    const { photos = [] } = viewModel

    // const [state, dispatch] = React.useReducer((state, action) => ({ ...state, ...action }), {})


    React.useEffect(() => {
        // console.log('viewModel', viewModel)
    }, [])

    let Sidelength = `calc((100vw - ${spacingHorizontal} * 2 - ${spacingInner} * 2) / 3)`
    if (props.width) {
        Sidelength = `calc((${props.width} - ${spacingHorizontal} * 2 - ${spacingInner} * 2) / 3)`
    }

    const show = (index: number) => {
        let urls = photos.map(i => {
            return typeof (i) == 'string' ? i : i.path
        })
        Taro.previewImage({
            urls: urls,
            current: urls[index]
        })
    }


    const add = () => {
        Taro.chooseImage({
            count: maxCount - photos?.length, // 默认9
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                setViewModel({ photos: [...photos, ...res.tempFiles] as any })
            }
        })

    }



    const del = (index: number) => {
        var tempPhotos = [...photos]
        tempPhotos.splice(index, 1)
        setViewModel({
            photos: tempPhotos as any
        })
    }


    let photos_length = viewModel?.photos?.length || 0

    return (
        <View style={{ ...styles.container, ...props.style, ...{ width: props.width }, }}>
            {
                photos?.map((i, idx) => {

                    return (
                        <View key={`sg-muti-picture-${idx}`} style={{
                            ...styles.item_container,
                            ...props.itemStyle,
                            marginTop: idx < 3 ? 0 : spacingInner, marginLeft: idx % 3 == 0 ? spacingHorizontal : spacingInner,
                            width: Sidelength, height: Sidelength,
                        }}>
                            <Image
                                style={{ width: '100%', height: '100%', }}
                                mode='aspectFill'
                                onClick={() => show(idx)}
                                src={typeof (i) == 'string' ? i : i.path}
                            />
                            {addEnabled &&
                                <View
                                    onClick={() => {
                                        del(idx)
                                    }}
                                    style={{ position: 'absolute', display: 'flex', justifyContent: 'flex-end', alignItems: "flex-start", right: 0, top: 0, width: '30px', height: '30px' }}>
                                    {
                                        deleteIcon ?
                                            <Image src={deleteIcon} style={{ width: '24px', height: '24px' }} mode='aspectFit' />
                                            :
                                            <View style={{
                                                width: '24px', height: '24px', color: 'white',
                                                fontSize: '18px', backgroundColor: "#00000055",
                                                display: 'flex', justifyContent: 'center', alignItems: "center"
                                            }}>{'x'}</View>
                                    }

                                </View>
                            }
                        </View>
                    )
                })
            }

            {
                (photos?.length < maxCount && addEnabled) && (
                    <View
                        onClick={() => add()}
                        style={{
                            ...styles.add_container,
                            ...props.addItemStyle,
                            marginTop: photos_length >= 3 ? spacingInner : 0, marginLeft: photos_length % 3 == 0 ? spacingHorizontal : spacingInner,
                            width: Sidelength, height: Sidelength,
                        }}>
                        {(() => {
                            if (React.isValidElement(props.addView)) return props.addView

                            return (
                                <View style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
                                    {addIcon && <Image src={addIcon} style={{ width: '37px', height: '37px', marginBottom: '4px', ...props.addIconStyle }} />}

                                    {addText && <Text style={{ fontSize: '12px', color: '#999999' }}>{addText}</Text>}

                                </View>
                            )
                        })()}
                    </View>

                )
            }

            {/* {hasPictureViewer && <PictureViewer bind={{ viewModel, setViewModel }} />} */}

        </View>
    )
}

const styles: Record<string, React.CSSProperties> = {
    container: {
        width: '100%',
        display: 'flex',
        flexDirection: 'row',
        flexWrap: 'wrap',

        // height: '500px',
        // backgroundColor: 'purple'
    },
    item_container: {
        backgroundColor: '#F3F3F3',
        display: 'flex',
        position: 'relative',
        borderRadius: '8px',
        overflow: 'hidden'
    },
    add_container: {
        backgroundColor: '#F3F3F3',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: '8px',
        overflow: 'hidden'
    },
}



